package cn.tools.jwt.server.utils;


import cn.tools.core.exception.BizException;
import cn.tools.core.exception.code.ExceptionCode;
import cn.tools.jwt.client.entiry.JwtHeadConfig;
import cn.tools.jwt.server.service.JwtTokenDecodeService;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author: e
 * @date: 2021/12/9
 * @description: 解密token
 */
@Slf4j
public class JwtTokenDecode implements JwtTokenDecodeService {
    private JwtHeadConfig jwtHeadConfig;

    public JwtTokenDecode(JwtHeadConfig jwtHeadConfig){
        this.jwtHeadConfig = jwtHeadConfig;
    }






    //获取公钥
    private PublicKey getPubKey() {
        PublicKey publicKey;
        try {
            File file = new File(jwtHeadConfig.getPubkey());
            InputStream resourceAsStream = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(resourceAsStream);
            byte[] keyBytes = new byte[0];
            keyBytes = new byte[resourceAsStream.available()];
            dis.readFully(keyBytes);
            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            publicKey = kf.generatePublic(spec);

        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BizException(ExceptionCode.NOT_FOUND.getMsg());
        }
        return publicKey;
    }



    @Override
    public Jwt tokenDecode(String jwt) {
        if(jwtHeadConfig.getHead().get("alg") != null && jwtHeadConfig.getHead().get("alg").equals("HS256")){
            return decodeHS256(jwt);
        }
        else if(jwtHeadConfig.getHead().get("alg") != null && jwtHeadConfig.getHead().get("alg").equals("RS256")){
            return decodeRS256(jwt);
        }
        throw new BizException("找不到配置信息");
    }


    //解析HS加密
    private Jwt decodeHS256(String jwt){
        return Jwts.parser().setSigningKey(jwtHeadConfig.getKey()).parse(jwt);
    }


    //解析RS加密
    private Jwt decodeRS256(String jwt){
        Jwt parse;
        try {
             parse = Jwts.parser().setSigningKey(getPubKey()).parse(jwt);
        }catch (Exception e){

            throw new BizException(ExceptionCode.JWT_PARSER_TOKEN_FAIL.getMsg());
        }
        return parse;
    }


}
